﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;

namespace SyringeControl
{
    using WinForms;
    using SyringeControl.AssemblySelectors;
    using System.ComponentModel;

    class SyringeContext : ApplicationContext
    {
        public SyringeContext(Form mainForm, MainFormController controller, IViewControlModel model, ISite site)
        {
            MainForm = mainForm;
            MainForm.Site = site;
        }
    }

    class MainFormController
    {
        readonly IControlView _controlView;
        readonly IAssemblySelector _assemblySelector;
        readonly IViewControlModel _model;
        IControlFactory _controlFactory;

        public MainFormController(IViewControlModel model, IControlView controlView, IControlFactory controlFactory, IAssemblySelector selector)
        {
            _model = model;
            _controlFactory = controlFactory;
            _controlView = controlView;
            _assemblySelector = selector;
            _model.OnChange(m => m.SelectedAssembly, asm => 
                _model.Types = GetValidTypes(asm));
            _model.OnChange(m => m.SelectedType, type => 
                _model.TestedControl = _controlFactory.Create(_model.SelectedType));
            _controlView.AssemblySelectionRequested += OnAssemblySelectionRequested;
            _controlView.ControlSetupRequested += OnSetupRequested;
        }

        public void SetAssemblyAndType(string assemblyPath, string controlTypeName)
        {
            _model.SelectedAssembly = new PathAssemblySelector(assemblyPath).SelectAssembly();
            _model.SelectedType = _model.SelectedAssembly.GetType(controlTypeName);
        }

        IList<Type> GetValidTypes(Assembly asm)
        {
            return (from t in asm.GetTypes()
                    where t.IsSubclassOf(typeof(Control)) && _controlFactory.IsValid(t)
                    select t).ToList();
        }

        void OnAssemblySelectionRequested(object sender, EventArgs e)
        {
            _model.SelectedAssembly = _assemblySelector.SelectAssembly();
        }
        void OnSetupRequested(object sender, EventArgs e)
        {
            
        }

    }
}
